package com.caffedev.ottollotto;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class OttollottoActivity extends Activity {
	
	long mSplashTime=500;
	boolean mPaused = false;
	boolean mSplashActive = true;
	
	
	private final static String TAG = "OttollottoActivity";

	private final String LOTTO_SITE_645 = "http://www.645lotto.net";
	private final String LAST_URL = "/resultall/dummy.asp";
	private final String LOTTO_SITE_KAISYU = "http://lotto.kaisyu.com/api?method=get&gno=";
	
	public static String GRWNO;
	public static String GRWDate;
	public static String FirstBall;
	public static String SecondBall;
	public static String ThirdBall;
	public static String FourthBall;
	public static String FifthBall;
	public static String SixthBall;
	public static String BonusBall;
	
	public static final int ID=0;
	public static final int INDEX_GRWNO=1;
	public static final int INDEX_GRWDATE=2;
	public static final int INDEX_FIRSTBALL=3;
	public static final int INDEX_SECONDBALL=4;
	public static final int INDEX_THIRDBALL=5;
	public static final int INDEX_FOURTHBALL=6;
	public static final int INDEX_FIFTHBALL=7;
	public static final int INDEX_SIXTHBALL=8;
	public static final int INDEX_BONUSBALL=9;
	
	private static final String KEY_ID="_ID";
	private static final String KEY_GRWNO="grwno";
	private static final String KEY_GRWDATE="grwdate";
	private static final String KEY_FIRSTBALL="firstball";
	private static final String KEY_SECONDBALL="secondball";
	private static final String KEY_THIRDBALL="thirdball";
	private static final String KEY_FOURTHBALL="fourthball";
	private static final String KEY_FIFTHBALL="fifthball";
	private static final String KEY_SIXTHBALL="sixthball";
	private static final String KEY_BONUSBALL="bonusball";
	
	private static final String DATABASE_NAME = "base.db";
	private static final String DATABASE_DIR = "/data/data/com.caffedev.ottollotto/databases/";
	private static final String DATABASE_ASSETS = "database/base.db";
	private static final String TABLE_NAME = "mTable";
	
	public static DatabaseHelper mHelper;
	public static SQLiteDatabase mDb;
	public static Cursor mCursor;
	//private myCursorAdapter ca;
	//private ExpandableListAdapter mAdapter;

	private int lastgrwno;
	
	private TextView alert;
	private Button ok;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.splash);
       
        alert = (TextView)findViewById(R.id.textView1);
        ok = (Button)findViewById(R.id.button1);
        ok.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
		    	finish();
			}
		});
        copyDatabase();
        mHelper = new DatabaseHelper(this);
	    mDb = mHelper.getWritableDatabase();
	    String query = "select * from "+TABLE_NAME+" order by _id desc";
	    mCursor = mDb.rawQuery(query, null);
        mCursor.moveToFirst();
        startManagingCursor(mCursor);
        
       
           
        Thread splashTimer = new Thread(){
        	public void run(){
        		try{
        		        updateLotto();
        		/*	long ms = 0;
        			while(mSplashActive && ms <= mSplashTime){
        				
        				sleep(100);
        				if(!mPaused){
        					ms += 100;
        				}
        			}*/
        			//startActivity(new Intent("com.google.app.splashy.CLEARSPLASH"));
        		        startActivity(new Intent(OttollottoActivity.this, OttollottoTab.class));        		    
        		}catch(Exception e){
        			e.printStackTrace();
        		}finally{
        			finish();
        		}
        	}
        };
        
        if(getNetworkType() == NETWORK_NONE){
        	
        	alert.setVisibility(View.VISIBLE);
        	ok.setVisibility(View.VISIBLE);
        	
	    	
	    }else{
	    	splashTimer.start();
	    }     
        
    }
    
    
    
    private static final int NETWORK_MOBILE = 0;
    private static final int NETWORK_WIFI = 1;
    //private static final int NETWORK_WIMAX = 2;
    private static final int NETWORK_NONE = 3;
    
    private int getNetworkType() {
    	  ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    	  NetworkInfo networkInfo_3G = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    	  NetworkInfo networkInfo_WIFI = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    	  // 4G
    	  //NetworkInfo networkInfo_WIMAX = manager.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);


    	  if (networkInfo_WIFI != null && networkInfo_WIFI.isConnectedOrConnecting()) {
    	   return NETWORK_WIFI;
    	  } else if (networkInfo_3G !=null && networkInfo_3G.isConnectedOrConnecting()) {
    	   return NETWORK_MOBILE;
    	  }/* else if (networkInfo_WIMAX !=null && networkInfo_WIMAX.isConnectedOrConnecting()) {
    	   return TYPE_WIMAX;
    	  }*/
    	  else
    		  return NETWORK_NONE;
    	 }

	private void copyDatabase(){

	   	File folder = new File(DATABASE_DIR);
	   	folder.mkdirs();
	   	
	   	File file = new File(DATABASE_DIR + DATABASE_NAME);
	       
	   	if(file.exists()){
	   		//Log.e(TAG,"database exists");
	   		return;
	       }
	       
	   	AssetManager assetManager = getResources().getAssets();
	   	try{
	   		InputStream is = assetManager.open(DATABASE_ASSETS, AssetManager.ACCESS_BUFFER);
	   		OutputStream out = new FileOutputStream(file);
	   		writeFile(is, out);
	   		out.close();
	   		is.close();
	   	}catch (Exception e){
	   		e.printStackTrace();
	   	}
	}
	
	private void writeFile(InputStream is, OutputStream os) throws IOException{
		int c = 0;
		while((c = is.read()) != -1)
			os.write(c);
		os.flush();
	}  
    private void updateLotto(){
		readJSONObject(LOTTO_SITE_645 + LAST_URL);
		   lastgrwno=	   Integer.parseInt(GRWNO);
		/*String query = "select GRWNO from "+TABLE_NAME;
		mCursor = mDb.rawQuery(query, null);
		mCursor.moveToLast();*/
		int no = Integer.parseInt(mCursor.getString(INDEX_GRWNO));
		
		if(lastgrwno == no){
			return;
		}
		
		else if((no - lastgrwno) == 1 )
				addNewItem();
			else 
			{
				for(int i = no+1; i <= lastgrwno;i++){
					readJSONObject2(LOTTO_SITE_KAISYU+i);
					addNewItem();
				}
		}
//		ca.notifyDataSetChanged();
	}
	private void addNewItem(){
		//mCursor.moveToLast();
		
		
		ContentValues arg = new ContentValues();
		
		
		arg.put(KEY_GRWNO, GRWNO);
		arg.put(KEY_GRWDATE, GRWDate);
		arg.put(KEY_FIRSTBALL, FirstBall);
		arg.put(KEY_SECONDBALL, SecondBall);
		arg.put(KEY_THIRDBALL, ThirdBall);
		arg.put(KEY_FOURTHBALL, FourthBall);
		arg.put(KEY_FIFTHBALL, FifthBall);
		arg.put(KEY_SIXTHBALL, SixthBall);
		arg.put(KEY_BONUSBALL, BonusBall);

		
		long rowId = mDb.insert(TABLE_NAME, null, arg);
	}
	private void readJSONObject2(String addr) {
        try{
        	//JSONArray ja = new JSONArray(DownloadHtml(addr));
        	//JSONObject jo = ja.getJSONObject(0);
        	JSONObject jo = new JSONObject(DownloadHtml(addr));
        	
        	JSONArray ja = jo.getJSONArray("nums");
        	
        	
        	GRWNO = jo.getString("gno");
        	GRWDate = jo.getString("gdate");
        	FirstBall = ja.getString(0);
        	SecondBall = ja.getString(1);
        	ThirdBall = ja.getString(2);
        	FourthBall = ja.getString(3);
        	FifthBall = ja.getString(4);
        	SixthBall = ja.getString(5);
        	BonusBall = jo.getString("bnum");

        	
        	
        }catch (JSONException e){
        	e.printStackTrace();
        }
		
	}
    private void readJSONObject(String addr) {
        try{
        	JSONArray ja = new JSONArray(DownloadHtml(addr));
        	JSONObject jo = ja.getJSONObject(0);
        	
        	GRWNO = jo.getString("GRWNO");
        	GRWDate = jo.getString("GRWDate");
        	FirstBall = jo.getString("FirstBall");
        	SecondBall = jo.getString("SecondBall");
        	ThirdBall = jo.getString("ThirdBall");
        	FourthBall = jo.getString("FourthBall");
        	FifthBall = jo.getString("FifthBall");
        	SixthBall = jo.getString("SixthBall");
        	BonusBall = jo.getString("BonusBall");
        	
        	
        }catch (JSONException e){
        	e.printStackTrace();
        }
		
	}

	private String DownloadHtml(String addr) {
		HttpGet httpget = new HttpGet(addr);
		DefaultHttpClient client = new DefaultHttpClient();
		StringBuilder html = new StringBuilder();
		String line=null;
		try {
			HttpResponse response = client.execute(httpget);
			BufferedReader br = new BufferedReader(new 
					InputStreamReader(response.getEntity().getContent()));
			for (;;) {
				line = br.readLine();
				if (line == null) break;
				html.append(line + '\n'); 
			}
			br.close();
		} 
		catch (Exception e) {
			e.printStackTrace();}
		
		
		return html.toString();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		super.onKeyDown(keyCode, event);
		mSplashActive = false;
		return true;
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		mPaused = true;
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mPaused = false;
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	@Override
	protected void onDestroy() {
		if(mDb.isOpen())
			mDb.close();
		if(!mCursor.isClosed())
			mCursor.close();
		super.onDestroy();
	}
}